#import "YQPSearchNewsModel.h"

#import "MYShopSearchVC.h"
#import "YQNavTitleView.h"
#import "YQSearchBaseBar.h"
#import "MYShopSearchScreenHeader.h"
#import "MYShopSearchGoodsCell.h"
#import "YQPAdvisorySelectTypeView.h"
#import "MYShopSearchScreenView.h"
#import "MYShopDetailsVC.h"
#define SCREENHEADER_H 44
@interface MYShopSearchVC ()<YQSearchBaseBarDelegate,UITableViewDelegate,UITableViewDataSource,MYShopSearchScreenViewDelegate>

@property (strong, nonatomic) NSSet *set;

@property (nonatomic, strong) YQSearchBaseBar * searchBar;
@property (nonatomic, strong) UIButton * cancelBtn;

@property (nonatomic, strong) YQBaseTableView * listTableView;

@property (nonatomic, strong) YQPAdvisorySelectTypeView * selctPriceTypeView;
@property (nonatomic, strong) YQPAdvisorySelectTypeView * saleTypeView;
@property (nonatomic, copy) NSArray * sortTitleArr;
@property (nonatomic, copy) NSArray * saleTitleArr;

@property (nonatomic, strong) MYShopSearchScreenHeader * screenHeaderView;

@property (nonatomic, copy) NSString * synthesizeSelectStr;

/// 分类查询结果数组
//@property (strong, nonatomic) NSMutableArray *sortArray;

//@property (strong, nonatomic) YQPSearchNewsModel *model;

/// 升降序 价格排序方式：asc->升序 desc->降序
@property (nonatomic, copy) NSString *priceSortStr;
/// 升降序 销量排序方式：asc->升序 desc->降序
@property (nonatomic, copy) NSString *saleSortStr;
//右边筛选View
@property (strong, nonatomic) MYShopSearchScreenView *searchView;

/// 品牌ids
@property (strong, nonatomic) NSMutableArray *brandIds;

/// 子品牌属性ids
@property (strong, nonatomic) NSMutableArray *subBrandIds;

@property (nonatomic, copy) NSString *minPrice;

@property (nonatomic, copy) NSString *maxPrice;

@property (strong, nonatomic) NSMutableDictionary *attrValuedic;

@end

@implementation MYShopSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = true;
    self.priceSortStr = @"";
    self.saleSortStr = @"desc";
    self.set = NSSet.new;
    self.sortTitleArr = @[kYQLS(@"综合"),kYQLS(@"价格降序"),kYQLS(@"价格升序")];

    self.saleTitleArr = @[kYQLS(@"降序"),kYQLS(@"升序")];

    //self.sortArray = NSMutableArray.new;
    
    self.subBrandIds = NSMutableArray.new;

    self.searchView.catalog3Id = self.selectID;
    self.searchView.delegate = self;
    [self setupRefresh];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.selctPriceTypeView cancelSelctTableView];
    [self.saleTypeView cancelSelctTableView];

}

- (void)setupRefresh
{
    self.listTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getUserSearchNewsSortsApi:YES];
    }];

    self.listTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.dataArr.count < 10) {
            [self.listTableView.mj_footer endRefreshing];
            return ;
        }
        self.page ++;

        [self getUserSearchNewsSortsApi:NO];
    }];
    if (self.selectID) {
        [self.listTableView.mj_header beginRefreshing];
    }
    self.listTableView.mj_header.automaticallyChangeAlpha = YES;
    self.listTableView.hidden = !self.selectID;
}
#pragma mark - 按照查询条件分页查询---三级资讯查询
- (void)getUserSearchNewsSortsApi:(BOOL)isReload
{
    if (isReload) {
        self.page = 1;
    }
    NSMutableDictionary *dic = NSMutableDictionary.new;

    dic[@"attrValueList"] = self.brandIds;// (Array[APP端搜索参数接收], optional): 平台属性参数接收 ,
    dic[@"catalog3Id"] = self.selectID;// (string, optional): 三级分类ID ,
    dic[@"keyword"] = self.searchBar.searchBar.text;// (string, optional): 搜索关键字 ,
    dic[@"limit"] = @(10);// (integer, optional): 每页大小：默认为10 ,
    dic[@"pageNo"] = @(self.page);// (integer, optional): 当前页码：默认为1 ,
    dic[@"priceSort"] = self.priceSortStr;// (string, optional): 价格排序方式：asc->升序 desc->降序 ,
    dic[@"salesVolumeSort"] = self.saleSortStr;// (string, optional): 销量排序方式：asc->升序 desc->降序 ,
    dic[@"endPrice"] = self.maxPrice.length >0?self.maxPrice:nil;// (number, optional): 结束价格区间 ,
    dic[@"startPrice"] = self.minPrice.length >0?self.minPrice:nil;// (number, optional): 开始价格区间
    
    YQSHOWLOADINGTIPS(kYQLS(@"加载中"))
    [YQPNetWorkingManager sendPostRequest:kPOST_SEARCH_APPLIST_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (self.page == 1) {
            [self.dataArr removeAllObjects];
        }
        YQPSearchNewsModel *model = [YQPSearchNewsModel mj_objectWithKeyValues:responseObject.data];
        [self.dataArr addObjectsFromArray:model.list];
        
        if (!self.selectID) {
            self.listTableView.hidden = (self.dataArr.count == 0);
            if (self.dataArr.count == 0 && ([self.searchBar.searchBar.text removeStringSpace].length != 0)) {
                kMBMesHUD(kYQLS(@"未查询到相关商品"));
            }
        }
        YQPNewsEntityModel *entityModel = self.dataArr.firstObject;
        if (!self.selectID) {
            self.searchView.catalog3Id = entityModel.catalog3Id;
        }
        
        [self.listTableView reloadData];
        [self.listTableView.mj_header endRefreshing];
        [self.listTableView.mj_footer endRefreshing];
        if(self.page == model.totalPage.integerValue) {
            [self.listTableView.mj_footer endRefreshingWithNoMoreData];
        }

    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error);
        [self.listTableView.mj_header endRefreshing];
        [self.listTableView.mj_footer endRefreshing];
    }];
}

-(void)setupView {
    [super setupView];
    self.synthesizeSelectStr = kYQLS(@"综合");
    YQNavTitleView *navView = [YQNavTitleView new];
    navView.frame = CGRectMake(0, 0, kScreenWidth, 44);
    navView.intrinsicContentSize = CGSizeMake(kScreenWidth, 44);
    self.navigationItem.titleView = navView;
    
    UIView *bgView = [UIView new];
    [navView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 44));
    }];
    
    [bgView addSubview:self.searchBar];
    [bgView addSubview:self.cancelBtn];
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.searchBar.mas_centerY).mas_equalTo(0);
        make.right.mas_equalTo(-12);
        make.height.mas_equalTo(20);
    }];
    
    [self.view addSubview:self.listTableView];

}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    YQPNewsEntityModel *model = self.dataArr[indexPath.row];
    if(indexPath.row < self.dataArr.count) {
        
    }
    MYShopSearchGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSearchGoodsCell"];
    [cell.goodsIcon sd_setImageWithURL:[NSURL URLWithString:model.skuDefaultImg] placeholderImage:IMAGE_NAMED(@"")];
    cell.titleLb.text = model.skuName;//@"子初(Springbuds)母婴本色抽纸婴儿抽取式面巾纸家用纸";
    cell.priceLb.text = [NSString stringWithFormat:@"$%.2f",model.price.doubleValue];
    cell.payCountLb.text = [NSString stringWithFormat:@"%@%@",model.salesVolume,kYQLS(@"人付款")];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 112;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YQPNewsEntityModel *newsModel = self.dataArr[indexPath.row];
    YQPSkuAttrModel *model = newsModel.skuAttrValueList.firstObject;
    MYShopDetailsVC *detailsVC = [[MYShopDetailsVC alloc] init];
    detailsVC.skuId = newsModel.ID;//[NSString stringWithFormat:@"%@", model.skuId];
    [self.navigationController pushViewController:detailsVC animated:true];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MYShopSearchScreenHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYShopSearchScreenHeader"];
    
    self.screenHeaderView = header;
    [header.synthesizeBtn addTarget:self action:@selector(synthesizeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [header.sellBtn addTarget:self action:@selector(sellAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [header.screenBtn addTarget:self action:@selector(screenAction:) forControlEvents:(UIControlEventTouchUpInside)];
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}

#pragma mark - UITableViewDelegate, UITableViewDataSource end
#pragma mark -- lazy
- (YQBaseTableView *)listTableView {
    if (!_listTableView) {
        _listTableView = [[YQBaseTableView alloc] initWithFrame:CGRectMake(0, 0, kYQPScreenWidth , kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea) style:UITableViewStylePlain];//Height_NavBar + 44
        _listTableView.backgroundColor = UIColor.whiteColor;
        _listTableView.delegate = self;
        _listTableView.dataSource = self;

        [_listTableView registerNib:[UINib nibWithNibName:@"MYShopSearchScreenHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:@"MYShopSearchScreenHeader"];
        [_listTableView registerNib:[UINib nibWithNibName:@"MYShopSearchGoodsCell" bundle:nil] forCellReuseIdentifier:@"MYShopSearchGoodsCell"];
    }
    return _listTableView;
}
#pragma mark - 价格排序
-(YQPAdvisorySelectTypeView *)selctPriceTypeView {
    if (!_selctPriceTypeView) {
        ws(self);
        _selctPriceTypeView = [[YQPAdvisorySelectTypeView alloc] initWithFrame:CGRectMake(0, Height_NavBar+SCREENHEADER_H, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea) dataSource:self.sortTitleArr.copy selectStr:self.synthesizeSelectStr resultBlack:^(NSString * _Nonnull result, NSInteger index) {
            self.synthesizeSelectStr = result;
            if ([result isEqualToString:kYQLS(@"综合")]) {
                self.priceSortStr = @"";
            }else if ([result isEqualToString:kYQLS(@"价格降序")]) {
                self.priceSortStr = @"desc";
            }else if ([result isEqualToString:kYQLS(@"价格升序")]) {
                self.priceSortStr = @"asc";
            }
            //根据价格排序刷新接口
            [self getUserSearchNewsSortsApi:YES];
            self.screenHeaderView.synthesizeBtn.selected = NO;
            [self.screenHeaderView.synthesizeBtn setTitle:result forState:(UIControlStateNormal)];
            [weakself.selctPriceTypeView removeFromSuperview];
            weakself.selctPriceTypeView = nil;
        } cancelBlack:^{
            self.screenHeaderView.synthesizeBtn.selected = NO;
            [weakself.selctPriceTypeView removeFromSuperview];
            weakself.selctPriceTypeView = nil;
            [self.screenHeaderView setSynthString:self.synthesizeSelectStr];

        }];
    }
    return _selctPriceTypeView;
}
#pragma mark - 销量排序
-(YQPAdvisorySelectTypeView *)saleTypeView {
    if (!_saleTypeView) {
        ws(self);
        _saleTypeView = [[YQPAdvisorySelectTypeView alloc] initWithFrame:CGRectMake(0, Height_NavBar+SCREENHEADER_H, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea) dataSource:self.saleTitleArr.copy selectStr:self.synthesizeSelectStr resultBlack:^(NSString * _Nonnull result, NSInteger index) {
            
            if ([result isEqualToString:kYQLS(@"降序")]) {
                self.saleSortStr = @"desc";
            }else if ([result isEqualToString:kYQLS(@"升序")]) {
                self.saleSortStr = @"asc";
            }
            
            self.synthesizeSelectStr = result;
            //根据价格排序刷新接口
            [self getUserSearchNewsSortsApi:YES];
            
            [self.screenHeaderView.sellBtn setTitle:result forState:(UIControlStateSelected)];
//            self.screenHeaderView.synthesizeBtn.selected = NO;
            [weakself.selctPriceTypeView removeFromSuperview];
            weakself.selctPriceTypeView = nil;
        } cancelBlack:^{
//            self.screenHeaderView.synthesizeBtn.selected = NO;
            [weakself.selctPriceTypeView removeFromSuperview];
            weakself.selctPriceTypeView = nil;
        }];
    }
    return _saleTypeView;
}
#pragma mark -- lazy end

#pragma mark -- heaer Action
-(void)synthesizeAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.selctPriceTypeView showSelctTableView];
    } else {
        [self.selctPriceTypeView cancelSelctTableView];
    }

}
-(void)sellAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    [self.selctPriceTypeView cancelSelctTableView];
    if (!sender.selected) {
        self.saleSortStr = @"desc";
    }else {
        self.saleSortStr = @"asc";
    }
    //根据价格排序刷新接口
    [self getUserSearchNewsSortsApi:YES];
    if (sender.selected) {
        [self.saleTypeView showSelctTableView];
    } else {
        [self.saleTypeView cancelSelctTableView];
    }
}
-(void)screenAction:(UIButton *)sender {

//    [MYShopSearchScreenView showShopSearchScreenViewWithCatalog3Id:self.selectID ResultBlack:^(NSString * _Nonnull result) {
//
//    } cancelBlack:^{
//
//    }];
    [self.selctPriceTypeView cancelSelctTableView];
//    MYShopSearchScreenView *searchView = [[MYShopSearchScreenView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    searchView.catalog3Id = self.selectID;
    [self.searchView showSelctTableView];
}

- (MYShopSearchScreenView *)searchView
{
    if (!_searchView) {
        _searchView = [[MYShopSearchScreenView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _searchView.catalog3Id = self.selectID;
        _searchView.delegate = self;
    }
    return _searchView;
}

#pragma mark - MYShopSearchScreenViewDelegate--获取品牌代理传递来的两个数组属性
- (void)didSelectGoodItemGetBrandIds:(NSArray *)subBrandIds andMinPrice:(NSString *)minPrice andMaxPrice:(NSString *)maxPrice
{
    if (maxPrice) {
        self.maxPrice = maxPrice;
    }
    if (self.minPrice) {
        self.minPrice = minPrice;
    }
    
    
    self.set = [NSSet setWithArray:subBrandIds];
    self.brandIds = NSMutableArray.new;

    [self.brandIds addObjectsFromArray:(NSArray *)self.set];

    [self getUserSearchNewsSortsApi:YES];
}


#pragma makr -- YQSearchBaseBarDelegate
- (void)yq_searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    if (searchBar.text.length != 0) {
        self.searchBar.searchKey = searchBar.text;
        [self getUserSearchNewsSortsApi:YES];

    }
}
-(void)yq_textFieldShouldClear:(UITextField *)textField {
//    if (textField.text.length != 0) {
//        [self getUserSearchNewsSortsApi:YES];
//    }
    self.listTableView.hidden = YES;
}
-(void)yq_shouldChangeText:(NSString *)text {
    
}
#pragma makr -- YQSearchBaseBarDelegate end
#pragma makr -- lazy
-(UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:0];
        _cancelBtn.titleLabel.font = kSystemMedium(14);
        [_cancelBtn setTitleColor:HexColor(0x79C4C7) forState:(UIControlStateNormal)];
        [_cancelBtn setTitle:kYQLS(@"取消") forState:(UIControlStateNormal)];
        ws(self);
        [_cancelBtn addTapAction:^(id  _Nonnull sender) {
            [weakself.selctPriceTypeView cancelSelctTableView];
            [weakself.navigationController popViewControllerAnimated:true];
        }];
    }
    return _cancelBtn;
}

-(YQSearchBaseBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[YQSearchBaseBar alloc] initWithFrame:CGRectMake(12, 0, SCREEN_WIDTH - 68, 28)];
        _searchBar.top = 11;
        _searchBar.delegate = self;
        _searchBar.placeholderStr = kYQLS(@"搜索您想要的物品");
    }
    return _searchBar;
}
#pragma makr -- lazy end
@end
